package anonymouschat.security;

import java.io.Serializable;

import javax.crypto.SecretKey;

import anonymouschat.exceptions.InvalidTagException;
import anonymouschat.security.integrity.MacTag;

/**
 * Wrapper class of a serialized object and a MacTag of that object
 * This is used to check the integrity of files stored on the file system
 * @author Jason
 *
 */
public class SerializedObjectAndTag implements Serializable {

	private static final long serialVersionUID = 8069298856705435424L;
	
	/** Object wrapped by this class*/ 
	private Serializable object;
	/** Tag of the object wrapped by this class */
	private MacTag tagOfObj;
	
	/**
	 * Create new SerializedObjectAndTag from a Serializable object and the key to mac with
	 * @param ser
	 *     Object to tag, and save
	 * @param key
	 *     Key used to MAC the object
	 */
	public SerializedObjectAndTag(Serializable ser, SecretKey key){
		this.object = ser;
		this.tagOfObj = SecurityUtils.mac(ser, key);
	} 

	/**
	 * Verify the object's tag, and return the object if the tag is good
	 * @param tagkey
	 * 			key to verify against
	 * @return
	 * 			Serialized object wrapped in this class
	 * @throws InvalidTagException
	 * 			Thrown if the tag didn't match (ie integrity of the object is compromised)
	 */
	public Serializable getVerifiedObject(SecretKey tagkey) throws InvalidTagException{
		if (SecurityUtils.ver(object, tagOfObj, tagkey) ){
			return this.object;
		}
		else{
			throw new anonymouschat.exceptions.InvalidTagException("Could not retrieve the object because its tag was not verified.");
		}
	}

}
